import axios from 'axios';
import store from 'store';
import mpAdapter from 'axios-miniprogram-adapter';
import SystemUtil from 'utils/systemUtil';
import Storage from 'storage';

const isMiniprogram = process.env.isMiniprogram;
const $alert = SystemUtil.alert;

let serviceData = {
  timeout: 60 * 1000,
  validateStatus(status) {
    return status >= 200 && status < 300;
  }
}

let version = __wxConfig.envVersion;
if (isMiniprogram) {
  axios.defaults.adapter = mpAdapter;
  switch (version) {
    case 'develop':
      serviceData.baseURL = 'https://manli.mynatapp.cc/manli';
      // serviceData.baseURL = 'http://192.168.0.100:80/manli';
      // serviceData.baseURL = 'https://www.manlitech.com/manli';
      break;
    case 'trial':
      serviceData.baseURL = 'https://manli.mynatapp.cc/manli';
      break;
    case 'release':
      serviceData.baseURL = 'https://www.manlitech.com/manli';
      break;
    default:
      serviceData.baseURL = 'https://www.manlitech.com/manli';
  }
} else {
  serviceData.responseType = 'json';
  serviceData.baseURL = process.env.NODE_ENV === 'development' ? '/dev/' : '/manli/';
}

const service = new axios.create(serviceData);

const notCheck = ['wechat/getCodeFromWechatAuth', 'api/wechatMiniProgram/getCodeFromWechatAuth'];
const notVerify = ['wechat/saveUserLocation', 'api/wehcatshop/getAdvertisement', 'api/wehcatshop/letBuy', 'api/wehcatshop/goodsList'];

const toReloadPage = () => {
  Storage.removeSession('user');
  if (isMiniprogram) {
    let pages = getCurrentPages();
    let mainWin;
    for (let i = pages.length - 1; i >= 0; i--) {
      const page = pages[i];
      let win = page.window;
      if (!win.unReloadStatus) {
        mainWin = win;
        break;
      }
    }
    mainWin.location.reload();
  } else {
    window.location.reload();
  }
};

export default class Request {
  static post(url, data, needAlert = true, hasLogin = true) {
    let config = {};
    if (hasLogin && notCheck.indexOf(url) === -1) {
      let authToken = store.state.authToken;
      if (notVerify.indexOf(url) !== -1) {
        if (authToken !== null) {
          config = {
            headers: {
              auth_token_wechat: authToken
            }
          };
        }
      } else {
        if (authToken === null) {
          SystemUtil.hideLoading();
          toReloadPage();
          return window.Promise.reject('登录超时，请重新登录');
        }

        config = {
          headers: {
            auth_token_wechat: authToken
          }
        };
      }
    }

    return service.post(url, data, config).then(res => {
      res = res.data;
      let code = res.code;

      if (code !== 0) {
        if ([-2, -4].indexOf(code) !== -1) {
          toReloadPage();
          throw res.msg;
        }
        let msg = `${res.msg}(错误代码:${code})`;
        if (needAlert) {
          throw new Error(msg);
        } else {
          throw msg;
        }
      }

      let rows = res.rows;
      if (rows === null) {
        return {
          data: res.data,
          msg: res.msg,
          systemTime: res.systemTime
        };
      }
      return {
        data: res.data,
        rows,
        msg: res.msg,
        systemTime: res.systemTime
      };
    }).catch(error => {
      if (typeof error !== 'string') {
        $alert(error.message, '错误');
      }
      throw error;
    });
  }
}
